#pragma once
#include <iostream>
#include <unistd.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <sys/time.h>
#include <sys/resource.h>
#include "../comm/expand_file_exist.hpp"
#include "../comm/log.hpp"
#include <signal.h>

// 给runner设置资源限制
// setrlimit
using namespace Log;

void catchSig(int sigNum)
{
    std::cout << "接收到了信号: " << sigNum << std::endl;
}
namespace Runner
{
    // 执行对应的程序
    class runner
    {
    public:
        static void setProcLimit(int cpu_limit, int mem_limit)
        {
            // cpu
            struct rlimit cpu_rlimit;
            cpu_rlimit.rlim_cur = cpu_limit;
            cpu_rlimit.rlim_max = RLIM_INFINITY;
            setrlimit(RLIMIT_CPU, &cpu_rlimit);
            // mem
            struct rlimit mem_rlimit;
            mem_rlimit.rlim_cur = mem_limit * 1024; // 传xxKB
            mem_rlimit.rlim_max = RLIM_INFINITY;
            setrlimit(RLIMIT_AS, &mem_rlimit);
        }

        // 返回值 > 0：运行错误
        // 返回值 < 0: 内部程序出错
        // 返回值 == 0：正常
        static int run(const std::string &file_name, int cpu_limit, int mem_limit)
        {
            std::string excute = expand::Expand::Exe(file_name);

            umask(0);
            int stdin_fd = open(expand::Expand::Stdin(file_name).c_str(), O_CREAT | O_RDONLY, 0644);
            int stdout_fd = open(expand::Expand::Stdout(file_name).c_str(), O_CREAT | O_WRONLY, 0644);
            int stderr_fd = open(expand::Expand::Stderror(file_name).c_str(), O_CREAT | O_WRONLY, 0644);
            if (stdin_fd < 0 || stdin_fd < 0 || stdin_fd < 0)
            {
                logMessage(ERROR, "%s, %s, %d", "打开文件失败", __FILE__, __LINE__);
                return -1;
            }

            pid_t id = fork();
            if (id < 0)
            {
                logMessage(ERROR, "%s, %s, %d", "runner创建子进程失败", __FILE__, __LINE__);
                close(stdin_fd);
                close(stdout_fd);
                close(stderr_fd);
                return -2;
            }
            if (id == 0)
            {
                // 添加资源约束
                // 约束由上层指定
                // setProcLimit(cpu_limit, mem_limit);
                // child
                dup2(stdin_fd, 0);
                dup2(stdout_fd, 1);
                dup2(stderr_fd, 2);

                // ./temp/[2023-05-27:16:17:27].exe
                execl(excute.c_str(), excute.c_str(), nullptr);
                logMessage(ERROR, "进程替换失败，请检查代码!!!");
                exit(1);
            }
            else
            {
                close(stdin_fd);
                close(stdout_fd);
                close(stderr_fd);
                int status = 0;
                waitpid(id, &status, 0);
                // run模块只需要判断是否出异常s
                // 捕捉信号
                logMessage(DEBUG, "运行完毕: %d", status & 0x7F);
                return status & 0x7F; // 获取信号
            }
        }
    };
}